package com.leyou.gateway.task;

import com.leyou.gateway.client.AuthClient;
import com.leyou.gateway.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppTokenHolder {
    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    private String token;

    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProperties;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)  //fixedDelay:重新刷新时间间隔
    public void loadTokenTask() throws InterruptedException {
        while (true){
            try{
                 this.token = authClient.authorize(jwtProperties.getApp().getId(),
                        jwtProperties.getApp().getSecret());
                log.info("【网关服务】申请token成功");
                break;
            }catch (Exception e){
                log.error("【网关服务】申请token失败");
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    //获取token
    public String getToken(){
        return token;
    }
}
